package Thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

//创建线程池类
class MyThreadPool{
    //submit方法，实现任务的存储，将任务存储在阻塞队列中
    BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue();
    public void submit(Runnable runnable){
        try {
            blockingQueue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //创建线程池并执行阻塞队列里面的任务
    public MyThreadPool(int n){//n表示线程的数量
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                while (true){
                    try {
                        Runnable task = blockingQueue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }

    }
}

public class Demo23 {
    public static void main(String[] args) {
        MyThreadPool myThreadPool = new MyThreadPool(4);
        for (int i = 0; i < 1000; i++) {
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " hello" );
                }
            });
        }
    }
}
